﻿using D.ATN.Extensions;
using D.ATN.Models;
using D.ATN.UIUitl;
using System;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace D.ATN
{
    public partial class FrmEvn : Form
    {
        public FrmEvn()
        {
            InitializeComponent();
            this.dgvEnvList.SetGridDataViewStyle();
        }

        /// <summary>
        /// 加载窗口
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void FrmDb_Load(object sender, EventArgs e)
        {
            try
            {
                this.LoadColumn();

                this.cboSPCDbType.Items.Add("Orcale");
                this.cboSPCDbType.Items.Add("MySql");
                this.cboSPCDbType.Items.Add("PostgreSQL");
                this.cboSPCDbType.Items.Add("Redis");
                this.cboSPCDbType.Items.Add("MongoDB");
                this.cboSPCDbType.Items.Add("SqlServer");

                this.cboMESDbType.Items.Add("Orcale");
                this.cboMESDbType.Items.Add("MySql");
                this.cboMESDbType.Items.Add("PostgreSQL");
                this.cboMESDbType.Items.Add("Redis");
                this.cboMESDbType.Items.Add("MongoDB");
                this.cboMESDbType.Items.Add("SqlServer");

                this.cboSpcSidServiceName.Items.Add("SERVICE_NAME");
                this.cboSpcSidServiceName.Items.Add("SID");

                this.cboMesSidServiceName.Items.Add("SERVICE_NAME");
                this.cboMesSidServiceName.Items.Add("SID");

                await this.LoadEnvSettingsAsync();
            }
            catch (Exception ex)
            {

            }
        }

        /// <summary>
        /// 加载列
        /// </summary>
        private void LoadColumn()
        {
            DataGridViewTextBoxColumn idBoxColumn = new DataGridViewTextBoxColumn();
            idBoxColumn.ReadOnly = true;
            idBoxColumn.Name = "Id";
            idBoxColumn.HeaderText = "序号";
            idBoxColumn.DataPropertyName = "Id";
            dgvEnvList.Columns.Add(idBoxColumn);

            DataGridViewTextBoxColumn envNameBoxColumn = new DataGridViewTextBoxColumn();
            envNameBoxColumn.ReadOnly = true;
            envNameBoxColumn.Name = "Name";
            envNameBoxColumn.HeaderText = "名称";
            envNameBoxColumn.DataPropertyName = "Name";
            dgvEnvList.Columns.Add(envNameBoxColumn);

            DataGridViewButtonColumn delBoxColumn = new DataGridViewButtonColumn();
            delBoxColumn.ReadOnly = true;
            delBoxColumn.Name = "Delete";
            delBoxColumn.HeaderText = "操作";
            delBoxColumn.DefaultCellStyle.NullValue = "删除";
            dgvEnvList.Columns.Add(delBoxColumn);
        }

        /// <summary>
        /// 加载表格数据
        /// </summary>
        /// <returns></returns>
        private async Task LoadEnvSettingsAsync()
        {
            var entities = await ServiceLocator.MySqllite.Select<EnvSettingEntity>().ToListAsync();
            this.dgvEnvList.DataSource = entities;
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnSave_Click(object sender, EventArgs e)
        {
            var evnEntities = new EnvSettingEntity()
            {
                Name = txtName.Text,

                SPCAccount = txtSPCAccount.Text,
                SPCPwd = txtSPCPwd.Text,
                SPCDbType = cboSPCDbType.Text,
                SPCSid = txtSPCSID.Text,
                SPCIp = txtSPCIP.Text,
                SPCPort = txtSPCPort.Text,
                SPCSidOrServiceName = cboSpcSidServiceName.Text,
                SPCSearchPath = txtSpcSearchPath.Text,
                SPCDataBase = txtSpcDataBase.Text,

                MESAccount = txtMESAccount.Text,
                MESPwd = txtMESPwd.Text,
                MESDbType = cboMESDbType.Text,
                MESSid = txtMESSID.Text,
                MESIp = txtMESIP.Text,
                MESPort = txtMESPort.Text,
                MESSidOrServiceName = cboMesSidServiceName.Text,
                MESSearchPath = txtMesSearchPath.Text,
                MESDataBase = txtMesDataBase.Text,

                WebAPIIP = txtWebAPIIP.Text,
                WebAPIPort = txtWebAPIPort.Text,
                RTIp = txtRTIP.Text,
                RTPort = txtRTPort.Text,
                NonRTIp = txtNonRTIP.Text,
                NonRTPort = txtNonRTPort.Text,
            };

            var dbEntity = await ServiceLocator.MySqllite.Select<EnvSettingEntity>().Where(m => m.Name == evnEntities.Name).FirstAsync();
            if (dbEntity != null)
            {// 修改
                evnEntities.Id = dbEntity.Id;
                var updateRes = await ServiceLocator.MySqllite.Update<EnvSettingEntity>().SetSource(evnEntities).ExecuteAffrowsAsync();
                if (updateRes > 0)
                {
                    MessageBox.Show("修改成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("修改失败");
                }
            }
            else
            {// 新增
                var insertRes = await ServiceLocator.MySqllite.Insert<EnvSettingEntity>(evnEntities).ExecuteAffrowsAsync();
                if (insertRes > 0)
                {
                    MessageBox.Show("新增成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("新增失败");
                }
            }
        }

        /// <summary>
        /// 选择某一行后
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dgvEnvList_SelectionChanged(object sender, EventArgs e)
        {
            if (dgvEnvList.SelectedRows.Count == 1)
            {
                txtName.Text = dgvEnvList.SelectedRows[0].Cells["Name"].Value?.ToString();

                var envEntity = await ServiceLocator.MySqllite.Select<EnvSettingEntity>().Where(m => m.Name == txtName.Text).FirstAsync();
                if (envEntity != null)
                {
                    txtSPCAccount.Text = envEntity.SPCAccount;
                    txtSPCPwd.Text = envEntity.SPCPwd;
                    txtSPCIP.Text = envEntity.SPCIp;
                    txtSPCPort.Text = envEntity.SPCPort;
                    txtSPCSID.Text = envEntity.SPCSid;

                    txtSpcSearchPath.Text = envEntity.SPCSearchPath;
                    txtMesSearchPath.Text = envEntity.MESSearchPath;

                    txtSpcDataBase.Text = envEntity.SPCDataBase;
                    txtMesDataBase.Text = envEntity.MESDataBase;

                    if (envEntity.SPCSidOrServiceName != null)
                    {
                        cboSpcSidServiceName.SelectedItem = envEntity.SPCSidOrServiceName;
                    }

                    var spcDbType = envEntity.SPCDbType;

                    if (spcDbType == "Orcale")
                    {//Orcale
                        cboSPCDbType.SelectedIndex = 0;
                    }
                    else if (spcDbType == "MySql")
                    {//MySql
                        cboSPCDbType.SelectedIndex = 1;
                    }
                    else if (spcDbType == "PostgreSQL")
                    {//PostgreSQL
                        cboSPCDbType.SelectedIndex = 2;
                    }
                    else if (spcDbType == "Redis")
                    {//Redis
                        cboSPCDbType.SelectedIndex = 3;
                    }
                    else if (spcDbType == "MongoDB")
                    {//MongoDB
                        cboSPCDbType.SelectedIndex = 4;
                    }
                    else if (spcDbType == "SqlServer")
                    {//SqlServer
                        cboSPCDbType.SelectedIndex = 5;
                    }



                    txtMESAccount.Text = envEntity.MESAccount;
                    txtMESPwd.Text = envEntity.MESPwd;
                    txtMESIP.Text = envEntity.MESIp;
                    txtMESPort.Text = envEntity.MESPort;
                    txtMESSID.Text = envEntity.MESSid;
                    if (envEntity.MESSidOrServiceName != null)
                    {
                        cboMesSidServiceName.SelectedItem = envEntity.MESSidOrServiceName;
                    }


                    txtWebAPIIP.Text = envEntity.WebAPIIP;
                    txtWebAPIPort.Text = envEntity.WebAPIPort;

                    txtRTIP.Text = envEntity.RTIp;
                    txtRTPort.Text = envEntity.RTPort;

                    txtNonRTIP.Text = envEntity.NonRTIp;
                    txtNonRTPort.Text = envEntity.NonRTPort;

                    var mesDbType = envEntity.MESDbType;

                    if (mesDbType == "Orcale")
                    {//Orcale
                        cboMESDbType.SelectedIndex = 0;
                    }
                    else if (mesDbType == "MySql")
                    {//MySql
                        cboMESDbType.SelectedIndex = 1;
                    }
                    else if (mesDbType == "PostgreSQL")
                    {//PostgreSQL
                        cboMESDbType.SelectedIndex = 2;
                    }
                    else if (mesDbType == "Redis")
                    {//Redis
                        cboMESDbType.SelectedIndex = 3;
                    }
                    else if (mesDbType == "MongoDB")
                    {//MongoDB
                        cboMESDbType.SelectedIndex = 4;
                    }
                    else if (mesDbType == "SqlServer")
                    {//SqlServer
                        cboMESDbType.SelectedIndex = 5;
                    }
                }
            }
        }

        /// <summary>
        /// 改变数据库类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboSPCDbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboSPCDbType.SelectedIndex == 0)
            {//Orcale
                this.txtSPCPort.Text = "1521";
            }
            else if (cboSPCDbType.SelectedIndex == 1)
            {//MySql
                this.txtSPCPort.Text = "3306";
            }
            else if (cboSPCDbType.SelectedIndex == 2)
            {//PostgreSQL
                this.txtSPCPort.Text = "5432";
            }
            else if (cboSPCDbType.SelectedIndex == 3)
            {//Redis
                this.txtSPCPort.Text = "6379";
            }
            else if (cboSPCDbType.SelectedIndex == 4)
            {//MongoDB
                this.txtSPCPort.Text = "27017";
            }
            else if (cboSPCDbType.SelectedIndex == 5)
            {//SqlServer
                this.txtSPCPort.Text = "1433";
            }
        }

        /// <summary>
        /// 改变数据库类型
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboMESDbType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cboMESDbType.SelectedIndex == 0)
            {//Orcale
                this.txtMESPort.Text = "1521";
            }
            else if (cboMESDbType.SelectedIndex == 1)
            {//MySql
                this.txtMESPort.Text = "3306";
            }
            else if (cboMESDbType.SelectedIndex == 2)
            {//PostgreSQL
                this.txtMESPort.Text = "5432";
            }
            else if (cboMESDbType.SelectedIndex == 3)
            {//Redis
                this.txtMESPort.Text = "6379";
            }
            else if (cboMESDbType.SelectedIndex == 4)
            {//MongoDB
                this.txtMESPort.Text = "27017";
            }
            else if (cboMESDbType.SelectedIndex == 5)
            {//SqlServer
                this.txtMESPort.Text = "1433";
            }
        }

        /// <summary>
        /// 点击删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void dgvEnvList_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (this.dgvEnvList.Columns[e.ColumnIndex].Name == "Delete")
            {
                //点击第一行button按钮事件
                int index = dgvEnvList.SelectedCells[0].RowIndex;

                var name = dgvEnvList.SelectedRows[0].Cells["Name"].Value.ToString();
                var processEntity = await ServiceLocator.MySqllite.Select<ProcessEntity>().Where(m => m.EvnName == name).FirstAsync();
                if (processEntity != null)
                {
                    MessageBox.Show($"禁止删除，有工作[{processEntity.Name}]正在使用"); return;
                }

                //获取所在行的值
                var id = int.Parse(dgvEnvList.SelectedRows[0].Cells["Id"].Value.ToString());
                // 删除
                var deleteRes = await ServiceLocator.MySqllite.Delete<EnvSettingEntity>().Where(m => m.Id == id).ExecuteAffrowsAsync();
                if (deleteRes > 0)
                {
                    MessageBox.Show("删除成功");
                    await this.LoadEnvSettingsAsync();
                }
                else
                {
                    MessageBox.Show("删除失败");
                }
            }
        }
    }
}
